<template>
  <div class="h5Template app-container">
    <!-- 筛选条件 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="70px" label-position="left">
      <el-form-item label="模板标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入模板标题" clearable />
      </el-form-item>
      <el-form-item label="模板状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择模板状态">
          <el-option label="禁用" :value="0" />
          <el-option label="启用" :value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable />
      </el-form-item> -->
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['system:template:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh-left" size="mini" @click="getList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-col>

      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />

    </el-row>

    <!-- 表格数据 -->
    <el-table v-if="refreshTable" v-loading="loading" :header-cell-style="{background: $store.state.app.theme.tableBack,color: $store.state.app.theme.tableColor}" stripe border :data="businessList" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange" @cell-dblclick="celldblclick">
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" width="200px" :show-overflow-tooltip="true" />
      <el-table-column label="套图预览" align="center" prop="carProperty" width="400px">
        <template slot-scope="scope">
          <div class="r_flex_center">
            <div v-for="(imgData ,index) in scope.row.sysOssList" :key="index" style="width: 100px; margin: 0 5px;">
              <!-- <img :src="imgData.url" alt="" style="width: 100%;"> -->
              <el-image
                :src="imgData.url"
                :preview-src-list="[imgData.url]"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" width="160px" prop="createTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 0"><el-tag type="info">禁用</el-tag></div>
          <div v-else-if="scope.row.status == 1"><el-tag type="success">启用</el-tag></div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermi(['system:template:edit', 'system:template:remove'])" label="操作" align="center">
        <template slot-scope="scope">
          <el-button v-hasPermi="['system:template:edit']" size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.parentId != 0" v-hasPermi="['system:template:remove']" size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row :gutter="24" class="mb8" style="margin: 20px 0px">
      <el-col :span="24" style="display: flex; justify-content: flex-end; padding: 0px">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :page-sizes="[10, 50, 100, 200]"
          :page-size="queryParams.pageSize"
          :current-page.sync="queryParams.pageNum"
          :total="totalPage"
          @current-change="handlePageChange"
          @size-change="
            newSize => {
              queryParams.pageSize = newSize;
              getList();
            }
          "
        />
      </el-col>
    </el-row>

    <!-- 对话框-修改 -->
    <el-dialog class="h5Template" :title="titleDialog === 'add' ? '新增H5模板信息' : '修改H5模板信息'" :visible.sync="openDialog" width="600px" append-to-body>
      <el-form ref="formDialog" :model="formDialog" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formDialog.title" placeholder="请输入标题（请勿重复命名）" />
        </el-form-item>
        <el-form-item label="URL链接" prop="url">
          <el-input v-model="formDialog.url" placeholder="请输入URL链接" />
        </el-form-item>
        <el-form-item label="UI效果图" prop="ossId">
          <Up-img :oss-image-url="ossImageUrl" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formDialog.status" placeholder="请选择" style="width: 100%">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoad" @click="submitForm">确 定</el-button>
        <el-button @click="openDialog = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { templateList, delTemplate, getTemplate, upTemplate, addTemplate } from '@/api/business/system'
import UpImg from '@/components/UpImg'
import { checkPermi } from '@/utils/permission' // 权限判断函数

export default {
  name: 'ProductSell',
  components: { UpImg },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 修改渠道loading
      submitLoad: false,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      businessList: [],
      // 对话框类型
      titleDialog: 'add',
      // 是否显示对话框
      openDialog: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1, // 当前页数
        pageSize: 10, // 分页大小
        title: '', // 渠道名
        createBy: ''
      },
      // logo地址
      imageLogoUrl: '',
      imageLogoName: '',
      // 数据总条数
      totalPage: 0,
      // 表单参数
      value1: '',
      value2: '',
      // 新增、修改参数
      formDialog: {
        title: '', // 渠道名
        status: 1,
        ossId: [],
        url: ''
      },
      H5Img: [],
      // 表单选中的书籍
      multipleSelection: [],
      // 新增表单校验
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        url: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        ossId: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      },
      // 上传图片选项
      ossImageUrl: [],
      dialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermi,
    // 钩子 - 删除事件
    upimginfo(file) {
      console.log(file, 'file')
    },
    // 上传预处理
    beforeAvatarUpload(file) {
      if (file.type.indexOf('image/') === -1) {
        this.$modal.msgError('文件格式错误，请上传图片类型,如:JPG,PNG后缀的文件。')
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.imageLogoName = file
        }
        this.uploadImg(file)
      }
    },
    // 查询列表
    getList() {
      this.loading = true
      templateList(this.queryParams).then(response => {
        this.businessList = response.rows
        this.totalPage = response.total
        this.loading = false
      }).finally(() => { this.loading = false })
    },
    // 新增按钮操作
    handleAdd() {
      if (this.formDialog.id) {
        this.formDialog = this.$options.data().formDialog
        this.ossImageUrl = this.$options.data().ossImageUrl
      }
      this.openDialog = true
      this.titleDialog = 'add'
    },
    // 搜索按钮操作
    handleQuery() {
      // this.queryParams.pageNum = 1, // 当前页数
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 删除按钮操作
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除')
        .then(function() {
          return delTemplate(row.id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.ossImageUrl = this.$options.data().ossImageUrl
      this.ossImageUrl = row.sysOssList.map(value => ({ id: value.ossId, ...value }))
      // console.log(this.ossImageUrl)
      this.loading = true
      const upId = row.id
      getTemplate(upId).then(response => {
        this.loading = false
        this.openDialog = true
        this.titleDialog = 'up'
        this.formDialog = response.data
      }).finally(() => { this.loading = false })
    },
    // 修改按钮操作
    submitForm() {
      this.formDialog.ossId = this.ossImageUrl.map(value => value.id)
      this.$refs['formDialog'].validate(valid => {
        if (valid) {
          this.submitLoad = true
          if (this.titleDialog === 'add') {
            addTemplate(this.formDialog)
              .then(() => {
                this.submitLoad = false
                this.openDialog = false
                this.getList()
                this.$modal.msgSuccess('新增成功')
              })
              .catch(() => {
                this.submitLoad = false
              })
          } else {
            upTemplate(this.formDialog)
              .then(() => {
                this.submitLoad = false
                this.openDialog = false
                this.getList()
                this.$modal.msgSuccess('修改成功')
              })
              .catch(() => {
                this.submitLoad = false
              })
          }
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: '',
        deptName: '',
        pdAmount: '',
        tag: '',
        leader: '',
        type: '',
        url: '',
        zkStatus: '1'
      }
      this.resetForm('form')
    },
    // 分页请求
    handlePageChange(data) {
      this.queryParams.pageNum = data
      this.getList()
    },
    // 双击复制
    celldblclick(row, column, cell, event) {
      if (!column.property) return
      if (!row[column.property]) return
      const oInput = document.createElement('input')
      oInput.value = row[column.property]
      document.body.appendChild(oInput)
      oInput.select()
      document.execCommand('Copy')
      this.$message.success({
        message: '复制成功',
        showClose: true
      })
      oInput.remove()
    },
    // 选择表格
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(val)
    }
  }
}
</script>

<style lang="scss" >
.h5Template {
  .el-upload-list {
    display: none;
  }
}
</style>

